<template>
  <div class="qm-materials">
    <!-- 顶部操作按钮（居右） -->
    <div class="toolbar-right">
      <el-button type="success" @click="openAddDialog">新增</el-button>
      <!-- <el-button type="primary" @click="handleExport">导出</el-button> -->
      <el-button type="danger" :disabled="!state.hasSelection" @click="handleBatchDelete">删除</el-button>
    </div>

     <el-form :inline="true" :model="table" class="demo-form-inline">
    <el-form-item label="单号">
      <el-input v-model="table.MaterialNo" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="loadTable">查询</el-button>
    </el-form-item>
  </el-form>
    <!-- 主表格 -->
    <el-table
      :data="table.rows"
      style="width:100%"
      border
      stripe
      @selection-change="onSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" label="序号" width="70" />
      <el-table-column prop="materialNo" label="单号" min-width="150" />
      <!-- <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.status === '已完成'">已完成</el-tag>
          <el-tag type="info" v-else>{{ row.status || '未完成' }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="designName" label="检验方案" min-width="140" />
      <el-table-column prop="materialsName" label="物料" width="120" />
      <el-table-column prop="materialCount" label="数量" width="120" />
      <el-table-column prop="suppliername" label="供应商" width="120" />
      <el-table-column prop="batchNumber" label="批次" width="120" />
<!--       <el-table-column prop="inspector" label="检验员" width="140" />
      <el-table-column prop="inspectTime" label="检验时间" width="180" />
      <el-table-column prop="auditor" label="审核人" width="140" />
      <el-table-column prop="auditTime" label="审核时间" width="180" /> 
      <el-table-column prop="auditRemark" label="审核备注" min-width="160" />-->
      <el-table-column prop="createName" label="创建人" width="140" />
      <el-table-column prop="createTime" label="创建时间" width="180" >
        <template v-slot="scope">
          {{ scope.row.createTime.substring(0,19).replace("T","") }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="{ row }">
         <!--  <el-button link type="primary" readonly @click="handleImport(row)">数据导入</el-button> -->
          <!-- <el-button link type="success" readonly @click="handleApprove(row)">审核</el-button> -->
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="table.PageIndex"
        v-model:page-size="table.PageSize"
        :page-sizes="[10,20,30,40]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="table.total"
      />
    </div>

    <!-- 新增对话框 -->
    <el-dialog v-model="dialog.visible" title="新增" width="600" align-center draggable>
      <el-form :model="form" :label-width="100">
        <el-form-item label="单号">
          <el-input v-model="form.materialNo" placeholder="自动生成" disabled />
        </el-form-item>
        <el-form-item label="物料" required>
          <el-input v-model="form.materialsName" placeholder="请选择数据" readonly @click="openMaterialDialog">
            <template #suffix>
              <el-icon><arrow-down /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="检验方案" required>
          <el-input v-model="form.designName" placeholder="请选择数据" readonly @click="openPlanDialog">
            <template #suffix>
              <el-icon><arrow-down /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="form.batchNumber" placeholder="自动带出" disabled />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="form.suppliername" placeholder="自动带出" disabled />
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="form.materialCount" placeholder="自动带出" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible=false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 嵌套对话框：选择物料 -->
    <el-dialog v-model="materialDlg.visible" title="请选择物料" width="900" align-center draggable>
      <div class="mini-toolbar">
        <el-icon class="icon"><grid /></el-icon>
        <el-icon class="icon"><search /></el-icon>
        <el-icon class="icon"><refresh /></el-icon>
        <el-icon class="icon"><setting /></el-icon>
      </div>
      <el-table :data="materialDlg.rows" style="width:100%" highlight-current-row @row-click="onPickMaterial">
        <el-table-column width="60">
          <template #default="{ row, $index }">
            <el-radio v-model="materialDlg.currentId" :label="row.id">{{ $index+1 }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="processroute" label="送货单号" min-width="140" />
        <el-table-column prop="specifications" label="物料编码" min-width="140" />
        <el-table-column prop="productName" label="物料名称" min-width="160" />
        <el-table-column prop="productcode" label="批次号" width="140" />
        <el-table-column prop="earlywarningvalue" label="数量" width="100" />
        <el-table-column prop="unit" label="供应商" min-width="160" />
        <el-table-column prop="productcode" label="库位" min-width="120" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="materialDlg.visible=false">取消</el-button>
          <el-button type="primary" @click="confirmPickMaterial">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 嵌套对话框：选择检验方案 -->
    <el-dialog v-model="planDlg.visible" title="请选择检验方案" width="900" align-center draggable>
      <el-table :data="planDlg.rows" style="width:100%" highlight-current-row @row-click="onPickPlan">
        <el-table-column width="60">
          <template #default="{ row, $index }">
            <el-radio v-model="planDlg.currentId" :label="row.id">{{ $index+1 }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="designName" label="名称" min-width="180" />
        <el-table-column prop="desugbType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag type="warning" v-if="row.desugbType==1">全检</el-tag>
            <el-tag type="danger" v-else>抽检</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inspectionMethod" label="抽检方式" width="120" />
        <el-table-column prop="designValue" label="值" width="120" />
        <el-table-column prop="designDescription" label="描述" min-width="180" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="planDlg.visible=false">取消</el-button>
          <el-button type="primary" @click="confirmPickPlan">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Grid, Search, Refresh, Setting } from '@element-plus/icons-vue'
import { APIs } from '@/Http/http'

// 是否使用本地假数据（后端未就绪时可切换）
const useMock = true // [[memory:8189833]]

// 表格数据与分页
const table = reactive({
  rows: [] as any[],

  PageIndex: 1,
  PageSize: 10,
  MaterialNo:"",
  totalCount:0,
  total: 1,
 

})

const state = reactive({
  hasSelection: false,
  selected: ref<any[]>([])
})

// 新增表单数据
const dialog = reactive({ visible: false })
const form = reactive({
  materialNo: "",
  materialsName: "",
  designName: "",
  batchNumber: "",
  suppliername: "",
  createName:"",
  materialCount: 0
})

// 物料选择对话框
const materialDlg = reactive({
  visible: false,
  rows:ref<any>([]),
  currentId: 0,
  currentRow: null as any
})

// 方案选择对话框
const planDlg = reactive({
  visible: false,
  rows:reactive<any>([]),
  currentId: 0,
  currentRow: null as any
})

onMounted(() => {
  loadTable()
})

/* watch(() => [table.pageIndex, table.pageSize], () => loadTable()) */

// 加载主表
const loadTable = () => {
/*   if (useMock) {
    table.rows = [
      {
        id: 1, orderNo: 'IQC202509020001', status: '已完成', planName: '2', materialTotal: 2000,
        result: 'NG', inspector: '(test)Tom', inspectTime: '2025-09-03 17:01:39', auditor: '(test)Tom',
        auditTime: '2025-09-05 19:35:18', auditRemark: '', creator: '(test)Tom', createdAt: '2025-09-02 14:49:19',
        updater: '(test)Tom', updatedAt: '2025-09-05 19:35:18'
      },
      {
        id: 2, orderNo: 'IQC202509020002', status: '已完成', planName: '锂电器', materialTotal: 2000,
        result: 'OK', inspector: '(test)Tom', inspectTime: '2025-09-03 17:01:53', auditor: '(test)Tom',
        auditTime: '2025-09-05 19:35:22', auditRemark: '', creator: '(test)Tom', createdAt: '2025-09-02 14:09:05',
        updater: '(test)Tom', updatedAt: '2025-09-05 19:35:22'
      }
    ]
    table.total = 2
    return
  } */
  APIs.get('/api/Read/GetExamineMater', { params: {MaterialNo:table.MaterialNo, PageIndex: table.PageIndex, PageSize: table.PageSize } }).then(res => {
    table.rows = res.data.data.data
    table.total = res.data.data.total
    table.totalCount=res.data.data.totalCount
  })
}

// 顶部按钮
const openAddDialog = () => {
  dialog.visible = true,
  form.materialNo= "",
  form.materialsName= "",
  form.designName="",
  form.batchNumber= "",
  form.suppliername= "",
  form.materialCount= 0
}

const handleExport = () => {
  if (useMock) {
    ElMessage.success('模拟导出成功')
    return
  }
  APIs.get('/api/Read/ExportIncoming', { responseType: 'blob' }).then(res => {
    const blob = new Blob([res.data], { type: 'application/octet-stream' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '来料检验列表.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  })
}

const handleBatchDelete = () => {
  const ids = state.selected.map((r:any)=>r.materialsId).toString();
  if (ids.length === 0) return
  ElMessageBox.confirm('确认删除所选记录吗？', '警告', { type: 'warning' }).then(() => {
    /* if (useMock) {
      table.rows = table.rows.filter(r => !ids.includes(r.id))
      state.selected = []
      state.hasSelection = false
      ElMessage.success('删除成功')
      return
    } */
    APIs.delete('/api/Write/AllDeleteExamineMater', { params: { codement: ids } })
    .then(res=>{
      if (res.data.code === 100) {
      ElMessage.success(res.data.msg || '删除成功')
      dialog.visible = false
      loadTable()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
    })
  })
}

// 行操作
const handleImport = (row: any) => {
  if (useMock) { ElMessage.success('模拟导入成功'); return }
  APIs.post('/api/Write/ImportIncoming', { id: row.id }).then(() => ElMessage.success('导入成功'))
}

const handleApprove = (row: any) => {
  ElMessageBox.confirm('确认审核通过吗？', '审核', { type: 'warning' }).then(() => {
    if (useMock) { ElMessage.success('模拟审核成功'); return }
    APIs.post('/api/Write/ApproveIncoming', { id: row.id }).then(() => loadTable())
  })
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该记录吗？', '警告', { type: 'warning' }).then(() => {
/*     if (useMock) {
      table.rows = table.rows.filter(r => r.id !== row.id)
      ElMessage.success('删除成功')
      return
    } */
    APIs.delete('/api/Write/DeleteMaterival', { params: { materialsId:row.materialsId } }).then(res=>{
      if (res.data.code == 100) {
      ElMessage.success(res.data.msg || '删除成功')
      loadTable()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
    })
  })
}

// 勾选
const onSelectionChange = (selection: any[]) => {
  state.selected = selection
  state.hasSelection = selection.length > 0
 
}

// 保存
const handleSave = () => {
  if (!form.materialsName) { ElMessage.warning('请选择物料'); return }
  if (!form.designName) { ElMessage.warning('请选择检验方案'); return }
  //if (useMock) { dialog.visible = false; ElMessage.success('模拟保存成功'); return }
  const payload = { materialId: form.materialsName, planId: form.designName }


  let command=reactive<any>({})
    command.materialNo=form.materialNo,
  command.materialsName=form.materialsName,
  command.designName=form.designName,
  command.batchNumber=form.batchNumber,
  command.suppliername=form.suppliername,
  command.materialCount=form.materialCount
  command.createName=form.createName;
  APIs.post('/api/Write/AddMaterival', command).then(res => {
    if (res.data.code === 100) {
      ElMessage.success(res.data.msg || '保存成功')
      dialog.visible = false
      loadTable()
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  })
}

// 打开/选择 物料
const openMaterialDialog = () => {
  materialDlg.visible = true
  loadMaterialOptions()
}

const loadMaterialOptions = () => {
  /* if (useMock) {
    materialDlg.rows = [
      { id: 11, sendNo: 'SH20250901001', materialCode: 'P-10001', materialName: '电机', batchNo: 'B001', quantity: 2000, supplier: 'ACME', location: 'A-01' },
      { id: 12, sendNo: 'SH20250901002', materialCode: 'P-10002', materialName: '锂电器', batchNo: 'B002', quantity: 2000, supplier: 'ACME', location: 'A-02' }
    ]
    return
  } */
  APIs.get('/api/Read/ShowProduct').then(res => { materialDlg.rows = res.data.data })
}

const onPickMaterial = (row: any) => {
  materialDlg.currentId = row.productid
  materialDlg.currentRow = row
}

const confirmPickMaterial = () => {
  const row = materialDlg.rows.find((r:any) => r.id === materialDlg.currentId)
  if (!row) { ElMessage.warning('请选择物料'); return }
  form.materialsName = row.productName,
  form.batchNumber = row.productcode
  form.suppliername = row.unit
  form.materialCount=row.earlywarningvalue

  materialDlg.visible = false
}

// 打开/选择 方案
const openPlanDialog = () => {
  planDlg.visible = true
  loadPlanOptions()
}

const loadPlanOptions = () => {
 /*  if (useMock) {
    planDlg.rows = [
      { designId: 1, designName: '2', desugbType: 1, inspectionMethod: '百分比', designValue: '10%', designDescription: '' },
      { designId: 2, designName: '锂电器', desugbType: 2, inspectionMethod: '间隔', designValue: '5', designDescription: '' }
    ]
    return
  }
  // 复用现有后端接口：质量方案列表
  APIs.get('/api/Read/ShowExaminDesign').then(res => { planDlg.rows = res.data.data }) */
  APIs.get("/api/Read/ShowExaminDesign").then(res=>{
    planDlg.rows=res.data.data;
  })
}

const onPickPlan = (row: any) => {
  planDlg.currentId = row.id
  planDlg.currentRow = row
}

const confirmPickPlan = () => {
  const row = planDlg.rows.find((r: any) => r.id === planDlg.currentId)
  if (!row) { ElMessage.warning('请选择检验方案'); return }
  form.designName = row.designName
  planDlg.visible = false
}

// 生成单号 IQCyyyyMMddHHmmssRRR
const generateOrderNo = (): string => {
  const now = new Date()
  const y = now.getFullYear()
  const m = String(now.getMonth() + 1).padStart(2, '0')
  const d = String(now.getDate()).padStart(2, '0')
  const hh = String(now.getHours()).padStart(2, '0')
  const mm = String(now.getMinutes()).padStart(2, '0')
  const ss = String(now.getSeconds()).padStart(2, '0')
  const r = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
  return `IQC${y}${m}${d}${hh}${mm}${ss}${r}`
}
</script>

<style scoped>
.toolbar-right { display:flex; justify-content:flex-end; gap:8px; margin-bottom:8px; }
.pager { display:flex; justify-content:flex-end; margin-top:8px; }
.dialog-footer { display:flex; justify-content:flex-end; gap:12px; }
.mini-toolbar { display:flex; justify-content:flex-end; gap:10px; margin-bottom:8px; }
.icon { color:#666; }


</style>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>

